package Tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class _145_BinaryTreePostorderTraversal {
    List<Integer> res1;
    //solution 1:recursive
    public List<Integer> postorderTraversal_1(TreeNode root) {
        this.res1 = new ArrayList<>();
        postorder(root);
        return res1;
    }

   public void postorder(TreeNode root) {
        if(root==null) return;
        postorder(root.left);
        postorder(root.right);
        res.add(root.val);
    }

    //solution 2:iterative
    LinkedList<Integer> res;
    public List<Integer> postorderTraversal(TreeNode root) {
        this.res = new LinkedList<>();
        if (root == null) return res;
        Stack<TreeNode> nodes = new Stack<>();
        nodes.add(root);
        while (!nodes.isEmpty()) {
            TreeNode tmp = nodes.pop();
            res.addFirst(tmp.val);
            if (tmp.left != null) {
                nodes.add(tmp.left);
            }
            if (tmp.right != null) {
                nodes.add(tmp.right);
            }
        }
        return res;
    }
}
